//
//  VideoViewModel.swift
//  NDAi
//
//  Created by 丸子 on 2024/7/1.
//

import UIKit

class VideoViewModel {
    var listModel:PaintingModel?
    var voiceArr:[VideoVoiceModel] = []
    var selectVoiceModel:VideoVoiceModel?
    var videoList:[VideoHistoryModel] = []

    var keyword:String = ""
    var isGenerated:Bool = false
    var messageStr:String = "输入主题开始生成吧～"
    let messageEventSubject = PublishSubject<(Int, String?)>()
    var style_id:Int?
    var proportion_id:Int?
    let reloadDataSubject = PublishSubject<Void>()
    let resultIdSubject = PublishSubject<String>()

    func getHomeVideoList() {
        RequestService.instance.homeVideoList(page: 1) {[weak self] list in
            self?.videoList = list ?? []
            self?.reloadDataSubject.onNext(())
        } failureClosure: { error in
            
        }
    }
    
    func checkWords(message:String){
        guard !isGenerated else {
            NDProgressHUD.show(message: "正在生成中....")
            return
        }
        if Appearance.shared.accoutModel == nil {
            //登录
            GlobalRx.loginSubject.onNext(())
            return
        }
        isGenerated = true
        self.messageStr = "思考中..."
        self.messageEventSubject.onNext((1, nil))
        RequestService.instance.checkKeyword(message: message) { check in
            if check {
                self.errorCheck(message: message)
                NDProgressHUD.showError(title: "", subtitle: "你输入的内容包含违禁词，请输入输入.")
            }else {
                self.startChat(message: message)
            }
        } failureClosure: { error in
            self.isGenerated = false
        }
    }
    
    func startChat(message:String) {
        RequestService.instance.create_story(message: message) { data in
            self.isGenerated = false
            if let message = data {
                self.messageStr = ""
                self.startRealtimeTimer(latestMessage: message)
            }else {
                self.errorCheck(message: message)
            }
        } failureClosure: { error in
            self.errorCheck(message: message)
            self.isGenerated = false
        }
    }
    
    var realtimeTimer: Timer?
    func stopTimer() {
        realtimeTimer?.invalidate()
        realtimeTimer = nil
    }
    
    func startRealtimeTimer(latestMessage: AIStreamMessage?) {
        guard let latestMessage = latestMessage else { return }
        stopTimer()
        var location = 0
        realtimeTimer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { [weak self] timer in
            guard let self = self else { return }
            var content = ""
            var isFinished = false
            let speedLength = Int.random(in: 3...8)
            if location + speedLength <= latestMessage.data.count {
                let startIndex = latestMessage.data.index(latestMessage.data.startIndex, offsetBy: location)
                let endIndex = latestMessage.data.index(startIndex, offsetBy: speedLength)
                content = String(latestMessage.data[startIndex..<endIndex])
                location += speedLength
                isFinished = latestMessage.status == .finish && location >= latestMessage.data.count
            } else if latestMessage.status == .finish, location < latestMessage.data.count {
                content = String(latestMessage.data[latestMessage.data.index(latestMessage.data.startIndex, offsetBy: location)...])
                isFinished = true
            } else {
                return
            }
            var m = AIStreamMessage()
            m.identify = UUID().uuidString
            m.event = isFinished ? "finish" : "add"
            m.data = content
            self.messageStr = "\(self.messageStr)\(content)"
            self.messageEventSubject.onNext((1, nil))
//            XLog.d("【Stream】", m.data)
//            if self.realtimeMessage == nil {
//                self.realtimeMessage = m
//            }
//            let sm = self.realtimeMessage?.merge(m) ?? m
//            self.realtimeMessage = sm
//            updateStreamContent(message: sm, isDone: false)
            if m.status == .finish {
                self.messageEventSubject.onNext((2, nil))
//                updateStreamContent(message: sm, isDone: true)
//                self.realtimeMessage = nil
                self.isGenerated = false
                timer.invalidate()
            }
        }
    }
    
    func errorCheck(message:String){
        self.isGenerated = false
        self.messageStr = "生成错误请重试"
        self.messageEventSubject.onNext((-1, nil))
    }
    
    func getStyle(){
        NDProgressHUD.showLoading()
        RequestService.instance.videoStyle_list { model in
            NDProgressHUD.hide()
            self.listModel = model
            if let styleModel = model.style?.first {
                self.style_id = styleModel.id ?? 0
            }
            if let pModel = model.proportion?.first {
                self.proportion_id = pModel.id ?? 0
            }
            self.reloadDataSubject.onNext(())
        } failureClosure: { error in
            NDProgressHUD.hide()
        }
    }
    
    func getAudio(){
        NDProgressHUD.showLoading()
        RequestService.instance.videoVoice_list { models in
            NDProgressHUD.hide()
            self.voiceArr = models
            if !models.isEmpty {
                self.selectVoiceModel = models.first(where: { $0.isSelect == true } )
            }
            self.reloadDataSubject.onNext(())
        } failureClosure: { error in
            NDProgressHUD.hide()
        }
    }
    
    func create_video(title:String, message:String){
        if title.count <= 0 {
            NDProgressHUD.show(message: "请输入主题")
            return
        }
        guard let styleId = self.style_id else {
            NDProgressHUD.show(message: "请选择样式")
            return
        }
        guard let proportion_id = self.proportion_id else {
            NDProgressHUD.show(message: "请选择比例")
            return
        }
        guard let voice_id = self.selectVoiceModel?.id else {
            NDProgressHUD.show(message: "请选择人物声音")
            return
        }
        NDProgressHUD.showLoading()
        RequestService.instance.create_Video(title: title, message: message, style_id: styleId.string, proportion_id: proportion_id.string, voice_id: voice_id.string) { a in
            NDProgressHUD.hide()
            self.resultIdSubject.onNext(a)
        } failureClosure: { error in
            NDProgressHUD.showError(title: "", subtitle: error ?? "")
        }
    }
    
}
